﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using hcom;

namespace hcms
{
	// 找不到页面时转到此页
	public partial class error404 : System.Web.UI.Page
	{
		protected hcms.Admin.Model model = Global.model;
		protected void Page_Load(object sender, EventArgs e)
		{
			// 如果是静态页面，调用相应的模板重新建立静态页面。否则抛出“页面不存在”异常。
			string str = Request.Url.Query;
			//"?404;http://localhost:80/Articles/004-59779bb8-6bf5-4b95-a302-d41f0d1bea75-18.htm"
			String regex = @"^\?404;http://[^/]+/Articles/(\d+)-(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})\.htm";
			Match match = Regex.Match(Request.Url.Query, regex);
			if (match.Success)
			{
				string cid = match.Result("$1");
				string aid = match.Result("$2");
				int tid = Global.model.getArtTemplate(aid, cid);
				string url = string.Format("/Templates/a{0}.aspx?aid={1}&cid={2}&tid={0}", tid, aid, cid);
				Server.Execute(url);
				return;
			}

			// 从重定向表中取旧网址对应的新网址
			string errurl = str.Substring(5);
			Uri ur = new Uri(errurl);
			string path = ur.PathAndQuery;
			string strsql = string.Format("select redNewUrl from hcms_Redirect where redOldUrl = '{0}'", path.Replace("'", "''"));
			object obj = model.da.ExecuteScalar(strsql);
			if (obj != null)
			{
				Response.Redirect((string)obj);
				return;
			}

			// 页面不存在
			throw (new Exception(Request.Url.Query + " 页面不存在。"));
		}
	}
}